package com.thinkmore.mybatisplus.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
public class FillHandler implements MetaObjectHandler {

    public FillHandler() {
        System.out.println("FillHandler init");
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        System.out.println("insertFill");
        boolean hasSetter = metaObject.hasSetter("ctime");
        System.out.println("hassetter:" + hasSetter);
        if (hasSetter) {
            // ctime对应实体字段
            //严格填充,只针对非主键的字段,只有该表注解了fill 并且 字段名和字段属性 能匹配到才会进行填充(null 值不填充)
            strictInsertFill(metaObject, "ctime", LocalDateTime.class, LocalDateTime.now());
            //或下面这个，2者选其中
            //setFieldValByName("ctime", LocalDateTime.now(), metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        System.out.println("updateFill");
        boolean hasSetter = metaObject.hasSetter("utime");
        System.out.println("hassetter:" + hasSetter);
        if (hasSetter) {
            //当没有传参时，才赋值
            Object val = getFieldValByName("utime", metaObject);
            if (val == null) {
                //strictUpdateFill(metaObject, "utime", LocalDateTime.class, LocalDateTime.now());
                setFieldValByName("utime", LocalDateTime.now(), metaObject);
            }
        }
    }
}
